package edu.pku.sei.transformation.editor.controller.commands.link;

import edu.pku.sei.modeler.exceptions.FactoryNotFoundException;
import edu.pku.sei.modeler.model.common.ModelRegistry;
import edu.pku.sei.modeler.model.structure.MetaDiagram;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.structure.StructureFactory;
import edu.pku.sei.transformation.editor.model.CompositeTransformation;
import edu.pku.sei.transformation.editor.model.Transformation;
import edu.pku.sei.transformation.editor.model.TransformationFormalParameter;
import edu.pku.sei.transformation.editor.model.TypedModel;

public class TransformationFormalParameterCreateCommand
		extends
		AbstractLinkCreateCommand<TransformationFormalParameter, Transformation, TypedModel> {
	private MetaDiagram diagram = null;
	private MetaNode referenceNode = null;

	public TransformationFormalParameterCreateCommand(
			TransformationFormalParameter link, Transformation source) {
		super(link, source);
		diagram = source.getDiagram();
		if (source instanceof CompositeTransformation && diagram != null) {
			try {
				StructureFactory f = (StructureFactory) ModelRegistry
						.getRegistry().getStructureFactory(source.getModel());
				referenceNode = f.createMetaNode();
				referenceNode.setReferenceShape(true);
				referenceNode.setModelElement(target);
				referenceNode.setLocationX(100);
				referenceNode.setLocationY(100 + source.getModelParameter()
						.size() * 100);
				referenceNode.setWidth(100);
				referenceNode.setHeight(50);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (FactoryNotFoundException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void execute() {
		source.getModelParameter().add(link);
		link.setTypedModel(target);
		link.setTransformation(source);

		if (diagram != null && referenceNode != null) {
			referenceNode.setModelElement(target);
			diagram.getNodes().add(referenceNode);
		}

	}

	@Override
	public void undo() {
		source.getModelParameter().remove(link);
		link.setTypedModel(null);
		link.setTransformation(null);

		if (diagram != null && referenceNode != null)
			diagram.getNodes().remove(referenceNode);
	}

}
